package com.wanji.sdk.impl.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.wanji.protocol.api.DeviceMessage;
import com.wanji.protocol.api.DeviceMessageDecoder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

public class WebSocketDecoder extends DeviceMessageDecoder<WebSocketFrame> {
    @Override
    protected DeviceMessage toDeviceMessage(ChannelHandlerContext ctx, WebSocketFrame in) {
        try {
            if (in instanceof TextWebSocketFrame textFrame) {
                String text = textFrame.text();
                if (StrUtil.isNotBlank(text)) {
                    return JSONUtil.toBean(text, DeviceMessage.class);
                }
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(new TextWebSocketFrame("Error: " + e.getMessage()));
            return null;
        }
        return null;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        StaticLog.info("WebSocket client connected: {}", ctx.channel().remoteAddress().toString());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        StaticLog.info("WebSocket client disconnected: {}", ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        StaticLog.error("Exception caught in WebSocketServerHandler", cause);
        ctx.close();
    }
}
